package com.managertrade.controller;

import com.managertrade.common.Result;
import com.managertrade.dto.SysRoleDTO;
import com.managertrade.dao.mysql.entity.SysRole;
import com.managertrade.dao.mysql.repository.SysRoleRepository;
import com.managertrade.service.impl.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/roles")
public class SysRoleController {

    @Autowired
    private SysRoleRepository roleRepository;
    @Autowired
    private RoleService roleService;

    @GetMapping
    public Result<List<SysRoleDTO>> getAllRoles() {
        StopWatch stopWatch =  new StopWatch();
        stopWatch.start();
        List<SysRole> allSysRole = roleRepository.findAll();
        List<SysRoleDTO> collect = allSysRole.stream().map(SysRoleDTO::new).collect(Collectors.toList());
        stopWatch.stop();
        log.info("角色分页列表耗时：{}ms",stopWatch.getTotalTimeMillis());
        return Result.success(collect);
    }

    @GetMapping("/page")
    public Result<Page<SysRoleDTO>> getRolePage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        PageRequest pageable = PageRequest.of(page - 1, size, Sort.by("id").descending());
        Page<SysRole> rolePage = roleRepository.findAll(pageable);
        Page<SysRoleDTO> dtoPage = rolePage.map(SysRoleDTO::new);
        return Result.success(dtoPage);
    }

    @PostMapping
    public Result<Void> addRole(@RequestBody SysRoleDTO role) {
        roleService.addRole(role);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result<Void> updateRole(@PathVariable Long id, @RequestBody SysRoleDTO role) {
        role.setId(id);
        roleService.updateRole(role);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRole(@PathVariable Long id) {
        roleService.deleteRole(id);
        return Result.success();
    }

    @GetMapping("/{id}/permissions")
    public Result<Map<String, Object>> getRolePermissions(@PathVariable Long id) {
        return Result.success(roleService.getRolePermissions(id));
    }

    @PostMapping("/{id}/permissions")
    public Result<Void> updateRolePermissions(@PathVariable Long id, @RequestBody List<Long> permissionIds) {
        roleService.updateRolePermissions(id, permissionIds);
        return Result.success();
    }
}